var monthIncome = [];
var monthCost = [];

$(function(){
	// 月·统计图选择时间
    var monthDP1 =  $("#monthPicker1").datetimepicker({
        format: "YYYY-MM",
        locale: moment.locale('zh-cn'),
        showTodayButton:true,
        showClear:true,
        defaultDate:new Date()
    });
    
    // 年·统计图选择时间
    $("#yearPicker1").datetimepicker({
        format: "YYYY",
        locale: moment.locale('zh-cn'),
        showTodayButton:true,
        showClear:true,
        defaultDate:new Date()
    });
    
    // 月·收入、支出切换
    $("input[name='monthCheckbox']").bootstrapSwitch({
    	onText:$.i18n.prop("income"),
    	offText:$.i18n.prop("cost")
    });
    $("input[name='monthCheckbox']").on('switchChange.bootstrapSwitch', function(event, state) {
    	barMonthIncomeCost(monthIncome, monthCost);
    });
    
    // 年·收入、支出切换【暂时无用】
    $("input[name='yearCheckbox']").bootstrapSwitch({offText:$.i18n.prop("no_support")});
    
	// 收入记一笔
	$("#incomeBtn").click(function(){
		window.location.href = "record.html?type=" + Constant.accountType.income;
	});
	
	// 支出记一笔
	$("#costBtn").click(function(){
		window.location.href = "record.html?type=" + Constant.accountType.cost;
	});
	
	// 按月统计查询
    $(".account-month-search").unbind("click").bind("click", function(event){
    	// 遮罩层开启
    	showRequestLoaddingPart($("#ajaxLoading1"), 1);
    	// 参数
    	var dataParam = {statType:0, record:{likeTime:$("#monthDatetime").val()}};
    	var param = {data:dataParam, url:"/account/stat/default", isLoading:false, callback:function(response){
    		hideRequestLoaddingPart(1);
    		if(parseResult(response)){
				// 本月收支3D饼图
		    	pieMonthIncomeCost(response.pieStat);
		    	
		    	// 本月收入，支出-平面动画条形统计图
		    	monthIncome = response.income;
		    	monthCost = response.cost;
		    	barMonthIncomeCost(response.income, response.cost);
			}
    	}}
    	// ajax发送请求
    	$.myajax(param);
    	
		// 阻止事件冒泡，此乃查询按钮，不能打开日期选择层
		event.stopPropagation();
		return false;
	});
    
    // 按年统计查询
    $(".account-year-search").unbind("click").bind("click", function(event){
    	// 遮罩层开启
    	showRequestLoaddingPart($("#ajaxLoading2"), 2);
    	// 参数
    	var dataParam = {statType:1, record:{likeTime:$("#yearDatetime").val()}};
    	var param = {data:dataParam, url:"/account/stat/default", isLoading:false, callback:function(response){
    		hideRequestLoaddingPart(2);
    		if(parseResult(response)){
				// 本年收支3D饼图
				pieYearIncomeCost(response.pieStat);
				// 本年收支-平面动画折线统计图
				lineIncomeCost(response.income, response.cost);
			}
    	}}
    	// ajax发送请求
    	$.myajax(param);
    	
		// 阻止事件冒泡，此乃查询按钮，不能打开日期选择层
		event.stopPropagation();
		return false;
	});
});

$(window).ready(function(){
	$(".account-month-search").click();
	$(".account-year-search").click();
});

/**
 * 默认收支饼图
 */
function pieDefault(cvs_id, cvsTitle, tooltips, pieStat){
	var noZero = false;
	$.each(pieStat,function(i){
		if(pieStat[i] > 0){
			noZero = true;
		}
	});
	
	// 未曾有任何消费记录，那么显示统计图
	if(!noZero){
		var labels = [$.i18n.prop("income")+pieStat[0],$.i18n.prop("cost")+pieStat[1]];
		
		var pie = new RGraph.Pie({
	        id: cvs_id,
	        data: [50, 50],
	        options: {
	        	title: cvsTitle,
	        	titleY:8,
	        	textSize: 10,
	        	titleBold: false,
	        	textColor: "black",
	            titleFont: "Microsoft Yahei, NSimSun",
	            labels: labels,
	            // labelsSticksList: true,// 提示线
	            exploded: 10,
	            radius : 100,
	            tooltips : tooltips,
	            tooltipsEvent:"onmousemove",
	            textAccessible: false,
	            strokestyle: 'transparent',
	            clearto: 'white'
	        }
	    }).on('beforedraw', function (obj){
	    	// 清空缓存
	        RGraph.clear(obj.canvas, 'white')
	    }).roundRobin();
		
		return true;
	}
	
	return false;
}

/**
 * 月收支饼图
 */
function pieMonthIncomeCost(pieStat){
	// 清空画布
	var cxt=document.getElementById("pie_month_ic_cvs_id").getContext("2d");
    cxt.clearRect(0, 0, cxt.width, cxt.height);
	
    var cvsTitlePre = $("#monthDatetime").val();
    if(cvsTitlePre){
    	cvsTitlePre = cvsTitlePre + " ";
    }
    
	var cvsTitle = cvsTitlePre + $.i18n.prop("income_cost_rate_month_pie");
	
	var tooltips = [];
	$.each(pieStat,function(i){
		tooltips[i] = "￥" + pieStat[i];
	});
	
	// 判断是否需要设置默认饼图
	if(pieDefault("pie_month_ic_cvs_id", cvsTitle, tooltips, pieStat)){
		return;
	}
	
	var labels = [$.i18n.prop("income")+pieStat[0],$.i18n.prop("cost")+pieStat[1]];
	
	var pie = new RGraph.Pie({
        id: 'pie_month_ic_cvs_id',
        data: pieStat,
        options: {
        	title: cvsTitle,
        	titleY:8,
        	textSize: 10,
        	titleBold: false,
        	textColor: "black",
            titleFont: "Microsoft Yahei, NSimSun",
            labels: labels,
            exploded: 10,
            radius : 100,
            tooltips : tooltips,
            tooltipsEvent:"onmousemove",
            textAccessible: false,
            strokestyle: 'transparent',
            clearto: 'white'
        }
    }).on('beforedraw', function (obj){
    	// 清空缓存
        RGraph.clear(obj.canvas, 'white')
    }).roundRobin();
}

/**
 * 月收入，支出-平面动画条形统计图
 */
function barMonthIncomeCost(income, cost){
	// 清空画布
	var cxt=document.getElementById("bar_month_ic_cvs_id").getContext("2d");
    cxt.clearRect(0, 0, cxt.width, cxt.height);
	
    // 设置标题
	var data = income;
	
	var cvsTitlePre = $("#monthDatetime").val();
    if(cvsTitlePre){
    	cvsTitlePre = cvsTitlePre + " ";
    }
    
	var cvsTitle = cvsTitlePre + $.i18n.prop("income_rate_month_bar");
	var state = $("input[name='monthCheckbox']").bootstrapSwitch('state');
	if(!state){
		cvsTitle = cvsTitlePre + $.i18n.prop("cost_rate_month_bar");
		data = cost;
	}
    
	var yInside = false;
	var ylabelsOffsetx = 7;
	
	// X坐标
	var labels = [];
	$.each(data,function(i){
		labels[i] = i+1;
		if(data[i] >= 10000){
			yInside = true;
			ylabelsOffsetx = 0;
		}
	});
	
	var isShowAbove = true;
	var tooltips = [];
	$.each(data,function(i){
		tooltips[i] = "￥" + data[i];
		if(data[i] > 0){
			isShowAbove = false; 
		}
	});
	
	// 画图
	new RGraph.Bar({
        id: 'bar_month_ic_cvs_id',
        data: data,
        options: {
        	tooltips: tooltips,
        	tooltipsEvent:"onmousemove",
        	textSize: 10,
        	titleBold: false,
        	textColor: "black",
            titleFont: "Microsoft Yahei, NSimSun",
        	title: cvsTitle,
        	titleY:8,
            textAccessible: false,
            scaleThousand: "",
            scaleZerostart: false,// true显示y坐标0,false不显示y坐标0
            backgroundGridVlines: false,
            backgroundGridBorder: false,
            backgroundGridAutofitNumvlines: 0,
            //linewidth: 2,
            shadow: false,
            /*hmargin: 7,*/
            colors: ['Gradient(pink:red:#f33)', 'Gradient(green:#0f0)'],
            labelsAbove: isShowAbove, // 是否显示具体值
            labelsColor: "black",
            labelsAboveSize: 6,
            labelsAboveColor: "red",
            labelsAboveUnitsPost:"",
            textAngle: 70,// x文本倾斜度
            labels: labels,
            labelsOffsety: 5,
            ylabels:true,
            ylabelsOffsetx: ylabelsOffsetx,
            //ytickgap:0,
            ylabelsInside: yInside,
            /*noyaxis:true,*/
            clearto: 'white',
            /*variant: '3d',
            gutterBottom: 90,*/
            noaxes: false // 是否屏蔽坐标 尖尖
        }
    }).on('beforedraw', function (obj){
    	// 清空缓存
        RGraph.clear(obj.canvas, 'white')
    }).grow({frames: 30});
}

/**
 * 年收支饼图
 */
function pieYearIncomeCost(pieStat){
	// 清空画布
	var cxt=document.getElementById("pie_year_ic_cvs_id").getContext("2d");
    cxt.clearRect(0, 0, cxt.width, cxt.height);
	
    var cvsTitlePre = $("#yearDatetime").val();
    if(cvsTitlePre){
    	cvsTitlePre = cvsTitlePre + " ";
    }
    
	var cvsTitle = cvsTitlePre + $.i18n.prop("income_cost_rate_year_pie");
	
	var tooltips = [];
	$.each(pieStat,function(i){
		tooltips[i] = "￥" + pieStat[i];
	});
	
	// 判断是否需要设置默认饼图
	if(pieDefault("pie_year_ic_cvs_id", cvsTitle, tooltips, pieStat)){
		return;
	}
	
	var labels = [$.i18n.prop("income")+pieStat[0],$.i18n.prop("cost")+pieStat[1]];
	
	var pie = new RGraph.Pie({
        id: 'pie_year_ic_cvs_id',
        data: pieStat,
        options: {
        	title: cvsTitle,
        	titleY:8,
        	textSize: 10,
        	titleBold: false,
        	textColor: "black",
            titleFont: "Microsoft Yahei, NSimSun",
            labels: labels,
            // labelsSticksList: true,// 提示线
            exploded: 10,
            radius : 100,
            tooltips : tooltips,
            tooltipsEvent:"onmousemove",
            textAccessible: false,
            strokestyle: 'transparent',
            //tooltipsCoordsPage: true,
            clearto: 'white'
        }
    }).on('beforedraw', function (obj){
    	// 清空缓存
        RGraph.clear(obj.canvas, 'white')
    }).roundRobin();
}

/**
 * 年收支-平面动画条形统计图
 */
function lineIncomeCost(income, cost){
	// 清空画布
	var cxt=document.getElementById("line_ic_cvs_id").getContext("2d");
    cxt.clearRect(0, 0, cxt.width, cxt.height);
	
    var cvsTitlePre = $("#yearDatetime").val();
    if(cvsTitlePre){
    	cvsTitlePre = cvsTitlePre + " ";
    }
    
	var cvsTitle = cvsTitlePre + $.i18n.prop("income_cost_rate_year_line");
	
	var yInside = false;
	var ylabelsOffsetx = 7;
	
	var lineData = [];
	lineData.push(income);
	lineData.push(cost);
	
	// X坐标
	var labels = [];
	$.each(income,function(i){
		labels[i] = i + 1;
		if(income[i] >= 10000 || cost[i] >= 10000){
			yInside = true;
			ylabelsOffsetx = 0;
		}
	});
	
	var tooltips = [];
	var tooltips_income = [];
	var tooltips_cost = [];
	$.each(income,function(i){
		tooltips_income[i] = "￥" + income[i]; 
	});
	$.each(cost,function(i){
		tooltips_cost[i] = "￥" + cost[i]; 
	});
	tooltips[0]=tooltips_income;
	tooltips[1]=tooltips_income;
	/*$.each(income,function(i){
		tooltips[i] = "￥" + income[i];
	});*/
	
	var line = new RGraph.Line({
		id: 'line_ic_cvs_id',
		data: lineData,
		options: {
			tooltips: tooltips_income,// 暂时只能设置一个
        	tooltipsEvent:"onmousemove",
			title: cvsTitle,
			titleY:8,
			textSize: 10,
        	titleBold: false,
        	textColor: "black",
            titleFont: "Microsoft Yahei, NSimSun",
            scaleThousand: "",// 数值较大时，逗号分隔
            backgroundGridVlines: false,
            backgroundGridBorder: false,
            backgroundGridAutofitNumvlines: 0,
            labels: labels,
            ylabels:true,
            ylabelsOffsetx: ylabelsOffsetx,// y坐标间距
            //ytickgap:0,
            ylabelsInside: yInside,// y坐标值显示在里面还是外面
            labelsOffsety: 5,
			textAccessible: false,
			}
    }).on('beforedraw', function (obj){
    	// 清空缓存
        RGraph.clear(obj.canvas, 'white')
        
    }).unfoldFromCenterTrace();
}
